package com.jobs.producer0.demo;

import com.jobs.common.factory.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;

/**
 * 死信队列实战
 * 消费者01
 * @author xdh
 **/
public class TTLConsumer01 {

    //普通交换机名称
    public static final String NORMAL_EXCHANGE = "ttl3_normal_exchange";

    //死信交换机名称
    public static final String DEAD_EXCHANGE = "ttl3_dead_exchange";

    //普通队列名称
    public static final String NORMAL_QUEUE = "ttl3_normal_queue";
    //普通队列名称
    public static final String NORMAL_RK = "zhangsan";

    //死信队列名称
    public static final String DEAD_QUEUE = "ttl3_dead_queue";

    //死信队列名称
    public static final String DEAD_RKEY = "lisi";

    public static void main(String[] args) throws  Exception{

        Channel channel = RabbitMqUtils.getChannel();

        //声明死信和普通的交换机类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        //声明普通队列
        HashMap<String, Object> arguments = new HashMap<>();

        //过期时间
        arguments.put("x-message-ttl", 10000);
        //正常队列设置死信队列
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        //设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key", DEAD_RKEY);

        arguments.put("x-max-length", 6);

        //声明死信和普通队列
        channel.queueDeclare(NORMAL_QUEUE,true,false,false, arguments);

        channel.queueDeclare(DEAD_QUEUE,true,false,false,null);

        //绑定普通的交换机与普通的队列
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, NORMAL_RK);
        //绑定死信的交换机与死信的队列
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, DEAD_RKEY);
        System.out.println("等待接收消息......");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println("Consumer01接收的消息是：" + new String(message.getBody()));
        };

        channel.basicConsume(NORMAL_QUEUE,true,deliverCallback,consumerTag->{});
    }
}

